var jPlayerProxy = (function(){
	var _cache = {
		initState: false,
		current: -1,
		playMode: 1,	//0:单个循环 1:列表循环 2:随机播放
		volume: 1,		//音量
		volumeOpenKey: true,		//音量开关
		keyIndex:0
	}
	
	//事件触发器
	var action = function(funName){
		if(Return.Action && Return.Action[funName]){
			var arg = arguments;
			var params = [];
			if(arg.length > 1){
				for(var i = 1,len = arg.length; i < len; i++){
					params.push("arg["+i+"]");
				}
			}
			eval("Return.Action." + funName + "("+params.join(",")+")");
		}
	}
	
	var getTimeTxt = function(num){
		var d = new Date("2000/1/1");
		d = new Date(d.getTime() + Math.ceil(num * 1000));
		var h = d.getHours();
		if(h){
			return  (h < 10? "0" + h : h) + ":" + (d.getMinutes() < 10?"0"+d.getMinutes():d.getMinutes()) + ":" +  (d.getSeconds() < 10?"0"+d.getSeconds():d.getSeconds());
		}
		else{
			return  (d.getMinutes() < 10?"0"+d.getMinutes():d.getMinutes()) + ":" +  (d.getSeconds() < 10?"0"+d.getSeconds():d.getSeconds());
		}
	}
	
	var _nextTimer;
	
	var init = function(callback){
		if(!_cache.initState){
			_cache.jplay.jPlayer({
				ready: function() {
					if(!_cache.initState){
						_cache.initState = true;
						_cache.jplay.bind($.jPlayer.event.timeupdate, function(event){
							var e = event;
							eachDoms(function(dom){
								_cache.duration = event.jPlayer.status.duration;
								
								dom.find("[jplay='total_time']").html(getTimeTxt(Number(event.jPlayer.status.duration)));
								dom.find("[jplay='play_time']").html(getTimeTxt(Number(event.jPlayer.status.currentTime)));
								
								var w = dom.find("[jplay='progress_line']").width();
								var play_per = (event.jPlayer.status.currentPercentAbsolute/100);
								if($.browser.webkit){
									if(play_per >= 1){
										_cache.jplay.jPlayer("stop");
										if(_nextTimer){
											window.clearTimeout(_nextTimer);
										}
										_nextTimer = window.setTimeout(function(){
											switch(_cache.playMode){
												case 0:
													start();
													break;
												case 1:
													next();
													break;
												case 2:
													random();
													break;
											}
										}, 20);
										return;
									}
								}
								dom.find("[jplay='download_line']").css({width: (w * (event.jPlayer.status.seekPercent/100)) + "px"});
								dom.find("[jplay='play_line']").css({width: (w * play_per) + "px"});
							})
						});
						if($.browser.webkit){
							_cache.jplay.bind($.jPlayer.event.error, function(event){
								if(_cache.list && _cache.list.length > 1){
									if(_cache.playMode == 2){
										random();
									}
									else{
										next();
									}
								}
							});
						}
						
						setVolume(_cache.volume);
						openVolume(true);
                        window.setTimeout(function(){
                            if(callback){
                                callback();
                            }
                        }, 10);
					}
				},
				errorAlerts:false,
				ended: function() {
					if(!$.browser.webkit){
						switch(_cache.playMode){
							case 0:
								start();
								break;
							case 1:
								next();
								break;
							case 2:
								random();
								break;
						}
					}
				},
				play: function() {
					displayBtn("pause",true);
					displayBtn("play",false);
				},
				pause: function(){
					displayBtn("pause",false);
					displayBtn("play",true);
				},
				stop: function(){
					displayBtn("pause",false);
					displayBtn("play",true);
				},
				volume: _cache.volume,
				swfPath: "statics/web/js",
				supplied: "mp3"
			});
			if(_cache.doms){
				for(var i = 0, len = _cache.doms.length; i < len; i++){
					bindBtn(_cache.doms[i]);
				}
			}
		}
		else{
			if(callback){
				callback();
			}
		}
	}
	
	var eachDoms = function(callback){
		for(var i = 0,len = _cache.doms.length; i < len; i++){
			if(callback){
				callback(_cache.doms[i]);
			}
		}
	}

	var displayBtn = function(type,isShow){
		if(isShow){
			eachDoms(function(dom){
				dom.find("[jplay='"+type+"']").show();
			})
		}
		else{
			eachDoms(function(dom){
				dom.find("[jplay='"+type+"']").hide();
			})
		}
	}

	//绑定按钮事件
	var bindBtn = function(dom){
		dom.find("[jplay]").mousedown(function(e){
			if($.browser.msie){
				event.cancelBubble=true;
			}else{
				e.stopPropagation();
				e.preventDefault();
			}	//停止冒泡
		})
		
		dom.find("[jplay='progress_line']").click(function(e){
			var outW = e.clientX - $(this).offset().left;
			var downBox = dom.find("[jplay='progress_line']");
			if(outW > downBox.width()){
				outW = downBox.width()
			}
			var persent = outW / downBox.width();
			_cache.jplay.jPlayer("play",persent * _cache.duration);
		});
		
        dom.find("[jplay='volume_button']").bind("mousedown", function(e){
            _cache.setVolumeState = true;
            //Show Div
            if(!_cache.vol_layer){
                _cache.vol_layer = Util.Mouse.GetLayOutBox();
            }
            if($.browser.msie){
				_cache.vol_layer[0].setCapture();
			}
            _cache.vol_layer.show();
            var line = dom.find("[jplay='volume_line']");
            
            _cache.vol_pos = {x: e.clientX, min: line.offset().left, max: line.offset().left + line.width()};
            
            _cache.vol_layer.unbind("mousemove").bind("mousemove", function(e){
                if(_cache.setVolumeState){
                    var x = e.clientX;
                    if(x < _cache.vol_pos.min){
                        x = _cache.vol_pos.min;
                    }
                    if(x > _cache.vol_pos.max){
                        x = _cache.vol_pos.max;
                    }
                    if(x != _cache.vol_pos.x){
                        _cache.vol_pos.x = x;
                        var w = x - _cache.vol_pos.min;
                        var persent = w/(_cache.vol_pos.max - _cache.vol_pos.min);
                        setVolume(persent);
                    }
                }
            }).unbind("mouseup").bind("mouseup", function(e){
                if(_cache.setVolumeState){
                    //Hide Div
                    _cache.setVolumeState = false;
                    if($.browser.msie){
                        _cache.vol_layer[0].releaseCapture();
                    }
                    if(_cache.vol_layer){
                        _cache.vol_layer.hide();
                    }
                }
            })
        }).css({cursor: "pointer"});
        
        

		dom.find("[jplay='play']").click(function(){
			//播放
			if(_cache.list && _cache.list.length && (!_cache.activeKey || _cache.activeKey != _cache.list[_cache.current].key)){
				_cache.current = 0;
				start();
			}
			else{
				if(_cache.list && _cache.list.length){
					_cache.jplay.jPlayer("play");
				}
			}
			return false;
		})
		dom.find("[jplay='pause']").click(function(){
			//暂停
			_cache.jplay.jPlayer("pause");
			return false;
		})
		dom.find("[jplay='next']").click(function(){
			//下一首
			if(_cache.playMode == 2){
				random();
			}
			else{
				next();
			}
			return false;
		})
		dom.find("[jplay='per']").click(function(){
			//上一首
			if(_cache.playMode == 2){
				random();
			}
			else{
				per();
			}
			return false;
		})
		dom.find("[jplay='stop']").click(function(){
			//停止
			_cache.jplay.jPlayer("stop");
			return false;
		})
		dom.find("[jplay='volume_open']").click(function(){
			openVolume(true);
			return false;
		})
		dom.find("[jplay='volume_close']").click(function(){
			openVolume(false);
			return false;
		})
		
		dom.find("[jplay='mode_0']").click(function(){
			setPlayMode(0);
			return false;
		})
		dom.find("[jplay='mode_1']").click(function(){
			setPlayMode(1);
			return false;
		})
		dom.find("[jplay='mode_2']").click(function(){
			setPlayMode(2);
			return false;
		})
	}
	
	//设置播放模式
	var setPlayMode = function(mod){
		_cache.playMode = mod;
		action("SetMode",_cache.playMode);
	}
	
	var playByKey = function(key){
		if(_cache.list){
			var ind = false;
			var list = _cache.list;
			for(var i = 0, len = _cache.list.length; i < len; i++){
				var item = _cache.list[i];
				if(item.key == key){
					ind = i;
					_cache.jplay.jPlayer("setMedia", item);
					_cache.activeKey = item.key;
					_cache.jplay.jPlayer("play");
					action("StartPlay",item);
				}
			}
			if(ind !== false){
				_cache.current = ind;
			}
		}
	}
	
	var start = function(){
		if(_cache.current >=0  && _cache.list[_cache.current]){
			_cache.jplay.jPlayer("setMedia", _cache.list[_cache.current]);
			_cache.activeKey = _cache.list[_cache.current].key;
			_cache.jplay.jPlayer("play");
			action("StartPlay",_cache.list[_cache.current]);
		}
	}

	//上一首执行函数
	var per = function(){
		if(_cache.list.length){
			if(_cache.current < 0){
				_cache.current = 0;
			}
			else{
				_cache.current--;
			}
			if(_cache.current < 0){
				_cache.current = _cache.list.length - 1;
			}
			start();
		}
	}
	
	//随机播放
	var random = function(){
		if(_cache.list){
			var len = _cache.list.length;
			var c = Math.floor(len * Math.random());
			if(c == _cache.list){
				c = 0;
			}
			_cache.current = c;
			
			start();
		}
	}
	
	//下一首执行函数
	var next = function(){
		if(_cache.list.length){
			if(_cache.current < 0){
				_cache.current = 0;
			}
			else{ 
				_cache.current++;
			}
			if(_cache.current >= _cache.list.length){
				_cache.current = 0;
			}
			start();
		}
	}
	
	//设置音量
	var setVolume = function(num){
		try{
		_cache.jplay.jPlayer( "volume", num);
		_cache.volume = num;
		eachDoms(function(dom){
			var w = dom.find("[jplay='volume_line']").width();
			dom.find("[jplay='volume_size_line']").css({width: (w * num) + "px"});
		})
		}catch(e){}
	}
	
	//打开/关闭音量
	var openVolume = function(isOpen){
		_cache.volumeOpenKey = isOpen;
		if(isOpen){
			_cache.jplay.jPlayer( "volume", _cache.volume);
		}
		else{
			_cache.jplay.jPlayer( "volume", 0);
		}
		eachDoms(function(dom){
			if(isOpen){
				dom.find("[jplay='volume_open']").hide();
				dom.find("[jplay='volume_close']").show();
			}
			else{
				dom.find("[jplay='volume_open']").show();
				dom.find("[jplay='volume_close']").hide();
			}
		})
	}
	
	//验证音乐是否存在
	var isExist = function(obj){
		var result = false;
		if(_cache.list){
			for(var i = 0,len = _cache.list.length; i < len; i++){
				if(_cache.list[i].name == obj.name && _cache.list[i]["mp3"] == obj["mp3"]){
					result = _cache.list[i].key;
				}
			}
		}
		return result;
	}
	
	var Return = {
		Action: null,	//事件源
		Bind: function(playDom,bindDoms){
			_cache.jplay = playDom;
			_cache.doms = bindDoms;
			displayBtn("pause",false);
			displayBtn("play",true);
			setVolume(_cache.volume);
			openVolume(true);
			eachDoms(function(dom){
				dom.find("[jplay='download_line']").css({width: 0});
				dom.find("[jplay='play_line']").css({width: 0});
			})
		},
		Add: function(arr, isplay){
			init(function(){
				if(!_cache.list){
					_cache.list = [];
				}
				var backArr = [];
				var result = false;
				var existCount = 0;
				var firstKey = false;
				for(var i = 0,len = arr.length; i < len; i++){
					var obj = arr[i];
					var r = isExist(obj);
					if(!r){
						obj.key = new Date().getTime() + _cache.keyIndex;
						_cache.keyIndex++;
						_cache.list.push(obj);
						backArr.push(obj);
						result = true;
						if(!firstKey){
							firstKey = obj.key;
						}
					}
					else{
						existCount++;
						if(!firstKey){
							firstKey = r;
						}
					}
				}
				action("AddMusic",backArr);
				if(isplay && firstKey){
					Return.Play(firstKey);
				}
				return {state: result, exist_count:existCount};
			});
		},
		Play: function(key){
			playByKey(key);
		},
		Stop: function(){
			_cache.jplay.jPlayer("stop");
		},
		Delete: function(key){
			var ind = -1;
			if(_cache.list){
				for(var i = 0,len = _cache.list.length; i < len; i++){
                    if(_cache.list[i].key == Number(key)){
						ind = i;
						break;
					}
                    
				}
			}
            
			if(ind != -1){
                try{
                    if(ind == _cache.current){
                        jPlayerProxy.Stop();
                    }
                }catch(e){}
				_cache.list.splice(ind,1);
				action("DeleteMusic",key);
			}
		}
	}
	
	return Return;
})();